<?php

/*
 * core/output.php
 *
 * Handle output as raw, json, ...other?
 */

static $globalErrors = '';

$printMethod = '_print' . Conf::$c['output']['type'];

if( !in_array( Conf::$c['output']['type'], array('RAW', 'JSON') ) )
{
	die( 'Configuration "outputType" is not correct (possible options: RAW, JSON)' );
}


/*
 * string buildJSON( $error, array );
 */
function buildJSON( $error, $array )
{
	$r = array( 'err'=>(is_null($error))?'null':$error, 'o'=>$array );
	return '[' . json_encode($r) . ']';

	/*
	if( $error == null )
		return '[null,' . json_encode($array) . ']';
	else
		return '[\'' . $error . '\',' . json_encode($array) . ']';
	*/
}

/*
 * void printRaw( error, array )
 * print raw output
 */
function _printRAW( $error, $array )
{
	$strArray = print_r( $array, $return=true );

	if( $error != null )
	{
		print( "<p style='color:red; font-size:30px; text-decoration:underline'> Error </p>\n" );
		print( "<p style='border:1px solid black; width:97%; padding:20px'>" . $error . "</p>\n" );
	}

	print( "<p style='color:green; font-size:30px; text-decoration:underline'> Output Array </p>\n" );
	print( "<p style='border:1px solid black; width:97%; padding:20px'>" . $strArray . "</p>\n" );
}

/*
 * void printJSON( error, array )
 * print JSON output
 */
function _printJSON( $error, $array )
{
	header('Content-Type: text/javascript');
	header('Cache-Control: no-cache');
	header('Pragma: no-cache');

	print( buildJSON( $error, $array ) );
}

/*
 * void output( error, array )
 * output values according to defined print method name.
 */
function output( $error, $array )
{
	global $printMethod;
	$printMethod( $error, $array );
}

/*
 * void error( strError )
 * output error and die
 */
function error( $error=null )
{
	global $printMethod;
	global $globalErrors;
	$error = (is_null($error)) ? $globalErrors : $error;
	$printMethod( $error, null );
	die();
}

/*
 * void resetError()
 * reset errors
 */
function resetError()
{
	global $globalErrors;

	$globalErrors = '';
}

/*
 * void setError( error )
 * add error to global errors
 */
function setError( $error )
{
	global $globalErrors;
	$globalErrors .=  $error . "\n";
}

/*
 * string getErrors()
 * return a copy of errors and reset it
 */
function getErrors()
{
	global $globalErrors;
	$errs = $globalErrors;
	$globalErrors = '';

	return $errs;
}

?>
